package com.by.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.by.bean.Product;
import com.by.bean.ResultBean;
import com.by.service.ProductService;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController//声明为控制类

public class ProductController extends BaseController{
@Autowired//自动注入
    ProductService productService;

@GetMapping("/export")
//导出操作(直接写入文件夹)
/*    public ResultBean simpleWriter(){
    String filename="C:\\Users\\li\\Desktop\\测试\\测试.xlsx";
    EasyExcel.write(filename, Product.class)
            .sheet("模板")
            .doWrite(()->{
                return data();
            });
            return success("响应成功");
}*/
//浏览器下载
public ResultBean simpleWriter(HttpServletResponse response)throws Exception{
    String filename=new String("测试数据.xls".getBytes(), StandardCharsets.ISO_8859_1);
    response.setContentType("application/vnd.ms-excel");
    response.setCharacterEncoding("utf8");
    response.setHeader("Content-disposition", "attachment;filename=" + filename );
    EasyExcel.write(response.getOutputStream(), Product.class)
            .sheet("模板")
            .doWrite(()->{
                return data();
            });
    return success("响应成功");
}
    private List<Product> data(){
        List<Product> list=productService.queryAll();
        return list;
    }
//    @GetMapping("imexcel")
    //导入操作(读取固定文件导入)
//    public ResultBean importExcel(){
//        String fileName = "C:\\Users\\li\\Desktop\\测试\\商品导入模板.xls";
//        EasyExcel.read(fileName,Product.class,new ExcelListener(productService)).sheet().doRead();
//        return success("响应成功");
//    }
    //上传导入
@PostMapping("imexcel")
@ResponseBody
    public ResultBean importExcel(@RequestParam("uploadFile") MultipartFile file)throws Exception{
        if(file!=null){
            InputStream in = file.getInputStream();
            EasyExcel.read(in,Product.class,new ExcelListener(productService)).sheet().doRead();
        }
        return success("响应成功");
    }
}
